package com.etc.dysys.admin.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.etc.dysys.admin.service.DoctorService;
import com.etc.dysys.admin.service.impl.DoctorServiceImpl;
import com.etc.dysys.entity.Doctor;

/**
 * Servlet implementation class DoctorServlet
 */
@WebServlet("/Doctor.action")
public class DoctorServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DoctorService ds = new DoctorServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = "query";

		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}

		if (op.equals("query")) {
			doQuery(request, response);
		} else if (op.equals("adddoctor")) {
			doAddDoctor(request, response);
		} else if (op.equals("deletedoctor")) {
			doDeleteDoctor(request, response);
		} else if (op.equals("selectdoctor")) {
			doSelectDoctorById(request, response);
		} else if (op.equals("updatedoctor")) {
			doUpdateDoctor(request, response);
		} else if (op.equals("updatestatus")) {
			doUpdateDoctorStatus(request, response);
		}

	}

	/**
	 * 根据医生id和状态，修改医生状态
	 * 
	 */
	protected void doUpdateDoctorStatus(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int dStatus = Integer.parseInt(request.getParameter("dStatus"));
		int dId = Integer.parseInt(request.getParameter("dId"));
		// 判断状态，取反
		if (dStatus == 0) {
			dStatus = 1;
		} else {
			dStatus = 0;
		}

		boolean flag = ds.updateDoctorStatus(dStatus, dId);

		doQuery(request, response);
	}

	/**
	 * 根据医生姓名dName，修改医生
	 */
	protected void doUpdateDoctor(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/*String dName = request.getParameter("dName");
		String dPassword = request.getParameter("dPassword");
		String dSex = request.getParameter("dSex");
		String dBirthday = request.getParameter("dBirthday");
		String dDesc = request.getParameter("dDesc");
		String dUrl = request.getParameter("dUrl");
		int dStatus = Integer.parseInt(request.getParameter("dStatus"));
		// 创建一个doctor对象
		Doctor doctor = new Doctor(dPassword, dSex, dBirthday, dDesc, dUrl, dStatus);
		boolean flag = ds.updateDoctorByName(doctor, dName);
		String msg = "修改成功";
		if (!flag) {
			msg = "修改失败";
		}

		PrintWriter out = response.getWriter();

		out.print(msg);
		out.close();*/
		
		
		// 接收用户表单提交过来的数据
				String dName = ""; 
				String dPassword = "";
				String dSex = "";
				String dBirthday =""; 
				String dDesc = "";
				String path ="";
		        int dStatus = 0;
                String src = "";
		        // 1.创建一个DiskFileItemFactory工厂对象、
		 		DiskFileItemFactory factory = new DiskFileItemFactory();
		 		// 2.得到一个文件上传处理的临时目录
		 		ServletContext servletContext = this.getServletConfig().getServletContext();
		 		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		 		factory.setRepository(repository);

		 		// ServletFileUpload核心对象来做文件的上传操作
		 		ServletFileUpload upload = new ServletFileUpload(factory);

		 	    // 解析request对象
				try {
					List<FileItem> items = upload.parseRequest(request);
			
					// List的处理 可以使用foreach,也可以使用迭代器
					Iterator<FileItem> iter = items.iterator();
					while (iter.hasNext()) {
						// FileItem 一个fileItem理解为一个表单的元素对象
						FileItem item = iter.next();
						// isFormFiled()如果这个item是表单域（表达实际上就是 非文件上传的部分,非文件域）
						if (item.isFormField()) {
			
							String name = item.getFieldName();
							// 设置编码格式
							String value = item.getString("utf-8");
			
							//System.out.println("isFormField name" + name + ",value" + value);
			
							// 判断 匹配
							if (name.equals("dName")) {
								dName = value;
							}
							else if (name.equals("dPassword")) {
								dPassword = value;
							}
							else if (name.equals("dSex")) {
								dSex = value;
							}
							else if (name.equals("dBirthday")) {
								dBirthday = value;
							}
							else if (name.equals("dDesc")) {
								dDesc = value;
							}
							else if (name.equals("dStatus")) {
								dStatus = Integer.parseInt(value);
							}
			
							//System.out.println("判断结果" + dName + "," + dPassword + "," + dSex + "," + dBirthday + ","+ dDesc + "," + dStatus);
						} else {
							// 文件域的处理
							String filedName = item.getFieldName();
							String fileName = item.getName();// 文件名
							String contentType = item.getContentType();
							boolean isInMemory = item.isInMemory();
							long sizeInBytes = item.getSize();// 大小
			
							// 文件路径
							path = request.getRealPath("/imgs/" + fileName);
							//System.out.println("path:" + path);
			                src = "/imgs/" + fileName;
							// 构建一个File对象出来
							File uploadedFile = new File(path);
							// 把文件写入指定的路径
							item.write(uploadedFile);
							//System.out.println("上传成功!");
						}
			
					}
					        
							Doctor doctor = new Doctor(dPassword, dSex, dBirthday, dDesc, src, dStatus);
							boolean flag = ds.updateDoctorByName(doctor, dName);
							doQuery(request, response);
					} catch (FileUploadException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		
	}

	/**
	 * 根据id查找单个医生
	 */
	protected void doSelectDoctorById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		int dId = Integer.parseInt(request.getParameter("dId"));
		Doctor doctor = ds.findDoctorById(dId);
		request.setAttribute("doctor", doctor);
		request.getRequestDispatcher("admin/experts-update.jsp").forward(request, response);

	}

	/**
	 * 移除医生
	 */
	protected void doDeleteDoctor(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int dId = Integer.parseInt(request.getParameter("dId"));
		boolean flag = ds.deleteDoctor(dId);
		doQuery(request, response);

	}

	/**
	 * 增加医生
	 */
	protected void doAddDoctor(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		  // 设置请求编码
		//   request.setCharacterEncoding("UTF-8");
		// 设置json格式
		// response.setContentType("application/json");
		  /*String dName = request.getParameter("dName"); 
		  String dPassword = request.getParameter("dPassword");
		  String dSex = request.getParameter("dSex"); 
		  String dBirthday =request.getParameter("dBirthday"); 
		  String dDesc = request.getParameter("dDesc"); 
		  String dUrl = request.getParameter("dUrl");
		  int dStatus = Integer.parseInt(request.getParameter("dStatus")); 
		  //创建一个doctor对象
		  Doctor doctor = new Doctor(dName, dPassword, dSex, dBirthday,dDesc, dUrl, dStatus);
		  boolean flag = ds.addDoctor(doctor);
		  if(flag) {
			  System.out.println("添加成功！");
		  }else {
			  System.out.println("添加失败！");
		  }
		  String msg = "添加成功";
		  if (!flag) {
			  msg = "添加失败"; 
			  }
		  
		  PrintWriter out = response.getWriter();
		  
		  out.print(msg);
		  out.close();*/
		 
		
		// 接收用户表单提交过来的数据
		String dName = ""; 
		String dPassword = "";
		String dSex = "";
		String dBirthday =""; 
		String dDesc = "";
		String path ="";
        int dStatus = 0;
        String src = "";
        // 1.创建一个DiskFileItemFactory工厂对象、
 		DiskFileItemFactory factory = new DiskFileItemFactory();
 		// 2.得到一个文件上传处理的临时目录
 		ServletContext servletContext = this.getServletConfig().getServletContext();
 		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
 		factory.setRepository(repository);

 		// ServletFileUpload核心对象来做文件的上传操作
 		ServletFileUpload upload = new ServletFileUpload(factory);

 	    // 解析request对象
		try {
			List<FileItem> items = upload.parseRequest(request);
	
			// List的处理 可以使用foreach,也可以使用迭代器
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				// FileItem 一个fileItem理解为一个表单的元素对象
				FileItem item = iter.next();
				// isFormFiled()如果这个item是表单域（表达实际上就是 非文件上传的部分,非文件域）
				if (item.isFormField()) {
	
					String name = item.getFieldName();
					// 设置编码格式
					String value = item.getString("utf-8");
	         
					//System.out.println("isFormField name" + name + ",value" + value);
	
					// 判断 匹配
					if (name.equals("dName")) {
						dName = value;
					}
					else if (name.equals("dPassword")) {
						dPassword = value;
					}
					else if (name.equals("dSex")) {
						dSex = value;
					}
					else if (name.equals("dBirthday")) {
						dBirthday = value;
					}
					else if (name.equals("dDesc")) {
						dDesc = value;
					}
					else if (name.equals("dStatus")) {
						dStatus = Integer.parseInt(value);
					}
	
					//System.out.println("判断结果" + dName + "," + dPassword + "," + dSex + "," + dBirthday + ","+ dDesc + "," + dStatus);
				} else {
					// 文件域的处理
					String filedName = item.getFieldName();
					String fileName = item.getName();// 文件名
					String contentType = item.getContentType();
					boolean isInMemory = item.isInMemory();
					long sizeInBytes = item.getSize();// 大小
	
					// 文件路径
					path = request.getRealPath("/imgs/" + fileName);
					//System.out.println("path:" + path);
	                src = "/imgs/" + fileName;
					// 构建一个File对象出来
					File uploadedFile = new File(path);
					// 把文件写入指定的路径
					item.write(uploadedFile);
					//System.out.println("上传成功!");
				}
	
			}
	
					Doctor doctor = new Doctor(dName,dPassword,dSex,dBirthday,dDesc,src,dStatus);			
					boolean flag = ds.addDoctor(doctor);
					doQuery(request, response);
	
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	/**
	 * 查询所有医生
	 */
	protected void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		List<Doctor> list = ds.getAllDoctor();
		request.setAttribute("list", list);
		request.getRequestDispatcher("admin/experts-list.jsp").forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
